package com.humingzhang.client.aws;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.humingzhang.client.FileClient;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * AWS存储SDK
 *
 * @author minghu.zhang
 */
public class AwsFileClient implements FileClient {

    private final AmazonS3 amazonS3;
    private final AwsConfig awsConfig;

    public AwsFileClient(AwsConfig awsConfig) {
        this.awsConfig = awsConfig;
        ClientConfiguration config = new ClientConfiguration().withProtocol(Protocol.HTTPS);
        AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(awsConfig.getEndpoint()
                , awsConfig.getRegion());
        AWSCredentials awsCredentials = new BasicAWSCredentials(awsConfig.getAccessKeyId(), awsConfig.getAccessKeySecret());

        this.amazonS3 = com.amazonaws.services.s3.AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
    }

    /**
     * 上传文件
     */
    @Override
    public String upload(String path, InputStream inputStream) {
        if (amazonS3.doesObjectExist(awsConfig.getBucketName(), path)) {
            throw new RuntimeException("文件已存在," + path);
        }
        amazonS3.putObject(awsConfig.getBucketName(), path, inputStream, new ObjectMetadata());
        return path;
    }

    /**
     * 下载文件
     */
    @Override
    public void download(String path, OutputStream output) throws IOException {
        if (!amazonS3.doesObjectExist(awsConfig.getBucketName(), path)) {
            throw new RuntimeException("文件不存在," + path);
        }

        S3Object s3Object = amazonS3.getObject(awsConfig.getBucketName(), path);
        S3ObjectInputStream input = s3Object.getObjectContent();
        IOUtils.copy(input, output);

        s3Object.close();
    }

    /**
     * 删除文件
     */
    @Override
    public void delete(String path) {
        if (!amazonS3.doesObjectExist(awsConfig.getBucketName(), path)) {
            throw new RuntimeException("文件不存在," + path);
        }
        amazonS3.deleteObject(awsConfig.getBucketName(), path);
    }

    @Override
    public void close() {
        amazonS3.shutdown();
    }
}
